package com.ydw.blog.aspest;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspest {
    @Pointcut("execution(* com.ydw.blog.web.*.*.*(..))")
    public void log(){};

    @Around("log()")
    public Object around(ProceedingJoinPoint jp){
        Object proceed = null;
        String name;
        Object[] args;
        String url = null;
        String ip = null;
        try {
            name = jp.getSignature().getDeclaringTypeName() + "." + jp.getSignature().getName() + "()";
            args = jp.getArgs();
//            for (Object obj :args) {
//                if (obj instanceof HttpServletRequest){
//                    url = ((HttpServletRequest) obj).getRequestURL().toString();
//                    ip = ((HttpServletRequest) obj).getHeader("x-forwarded-for");
//                    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//
//                        ip = ((HttpServletRequest) obj).getHeader("Proxy-Client-IP");
//                    }
//                    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//
//                        ip = ((HttpServletRequest) obj).getHeader("WL-Proxy-Client-IP");
//
//                    }
//
//                    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//
//                        ip = ((HttpServletRequest) obj).getRemoteAddr();
//
//                    }
//                }
//            }
            log.info("Request:{}", new RequestLog(url,ip,name,args));
            log.info("------------方法执行之前------------");
            proceed = jp.proceed();
            log.info("方法参数返回:{}",proceed);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;
    }
}
